package com.sync.mutiParse;

import java.util.concurrent.TimeUnit;

public final class FreeQueue {
	private static final int COUNT = 128;
	private Block[] blocks = new Block[COUNT];
	/**
	 * 扫描一次，如果有空闲块，返回，如果没有空闲块，返回null
	 * 
	 * @return
	 */
	public Block pollFree() {
		int i = 0;
		for (i = 0; i != COUNT; ++i) {
			if (blocks[i] == null) {
				blocks[i] = new Block();
				return blocks[i];
			}
			if (blocks[i].id == -1) {
				return blocks[i];
			}
		}
		return null;
	}

	/**
	 * 一直扫描，如果有空闲块，返回，没有空闲块循环，需要使用的重放线程，把id设置为-1
	 * 
	 * @return
	 */
	public Block takeFree() {
		int i = 0;
		while (true) {
			if (blocks[i] == null) {
				blocks[i] = new Block();
				return blocks[i];
			}
			if (blocks[i].id == -1) {
				return blocks[i];
			}
			i++;
			if (i == COUNT) {
				i = 0;
				try {
					TimeUnit.MICROSECONDS.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
